package com.ramos.kuaixiao.db;

import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteStatement;
import android.util.Log;

import com.ramos.kuaixiao.entity.FindOrderDetail;
import com.ramos.kuaixiao.utils.ToastUtils;

import java.util.ArrayList;
import java.util.List;

public class OrderDB {
    private static String TAG = "OrderDB";
    private static String TABLE_NAME = "OrderList";
    public static final String CREATE_TABLE_SQL;
    public static final String DROP_USERINFO;

    static {
        CREATE_TABLE_SQL = "CREATE TABLE " + TABLE_NAME + " (" + "did" + " INTEGER  ,"
                +"DealerId" + " CHAR(30)," + "CustomerId" + " CHAR(30)," + "CustomerName" + " CHAR(30)," +
                "EmployerId" + " CHAR(30)," + "EmployerName" + " CHAR(30)," + "OrderTotalPrice" + " CHAR(30)," + "PayType" + " CHAR(30)," +
                "DeliveryType" + " CHAR(30)," + "OrderStatus" + " CHAR(30)," + "DstAddr" + " CHAR(30)," +
                "Telephone" + " CHAR(30)," + "CommunicatePeople" + " CHAR(30)," + "OrderDate" + " CHAR(30)," + "OrderId" + " CHAR(30) PRIMARY KEY," +
                "HouseId" + " CHAR(30)," + "HouseName" + " CHAR(30)," + "DmsOrderId" + " CHAR(30)," + "OrderDetailList"
                + " CHAR(500),"+ "modifyTime" + " Long,"+ "Token" + " CHAR(50),"+ "comment" + " CHAR(50),"+"storeHouseId" + " CHAR(50));";
        DROP_USERINFO = "DROP TABLE IF EXISTS " + TABLE_NAME;
    }

    public int addAllOrder(List<FindOrderDetail> customer) {
        //deleteAll();
        SQLiteDatabase db = DBHelper.open();
        db.execSQL("DELETE FROM OrderList");
        String sql = "insert into OrderList(DealerId,CustomerId,CustomerName,EmployerId,EmployerName,OrderTotalPrice,PayType,DeliveryType," +
                "OrderStatus,DstAddr,Telephone,CommunicatePeople,OrderDate,OrderId,HouseId,HouseName,DmsOrderId,OrderDetailList,modifyTime,Token,comment,storeHouseId) " +
                "values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)";
        db.beginTransaction();
        Long a = System.currentTimeMillis();
        SQLiteStatement stmt = db.compileStatement(sql);
        for (int i = 0; i < customer.size(); i++) {
            stmt.bindString(1, customer.get(i).getDealerId() + "");
            stmt.bindString(2, customer.get(i).getCustmerId() + "");
            stmt.bindString(3, customer.get(i).getCustmerName() + "");
            stmt.bindString(4, customer.get(i).getEmployerId() + "");
            stmt.bindString(5, customer.get(i).getEmployerName() + "");
            stmt.bindString(6, customer.get(i).getOrderTotalPrice() + "");
            stmt.bindString(7, customer.get(i).getPayType() + "");
            stmt.bindString(8, customer.get(i).getDeliveryType() + "");
            stmt.bindString(9, customer.get(i).getOrderStatus() + "");
            stmt.bindString(10, customer.get(i).getDstAddr() + "");
            stmt.bindString(11, customer.get(i).getTelephone() + "");
            stmt.bindString(12, customer.get(i).getCommunicatePeople() + "");
            stmt.bindString(13, customer.get(i).getOrderDate() + "");
            stmt.bindString(14, customer.get(i).getOrderId() + "");
            stmt.bindString(15, customer.get(i).getHouseId() + "");
            stmt.bindString(16, customer.get(i).getHouseName() + "");
            stmt.bindString(17, customer.get(i).getDmsOrderId() + "");
            stmt.bindString(18, customer.get(i).getOrderDetailList() + "");
            stmt.bindString(19, customer.get(i).getModifyTime() + "");
            stmt.bindString(20, customer.get(i).getToken()+ "");
            stmt.bindString(21, customer.get(i).getComment()+ "");
            stmt.bindString(22, customer.get(i).getStoreHouseId()+ "");
            stmt.execute();
            stmt.clearBindings();
        }
        db.setTransactionSuccessful();
        db.endTransaction();
        Long b = System.currentTimeMillis();
        Log.i(TAG, String.valueOf(b - a));
        return 0;
    }

    public int updateAllOrder(List<FindOrderDetail> customer) {
        SQLiteDatabase db = DBHelper.open();
        db.beginTransaction();
        Long a = System.currentTimeMillis();
        if(customer != null && customer.size() >0){
            for (int i = 0; i < customer.size(); i++) {
                FindOrderDetail firstWarehouse = customer.get(i);
                    ContentValues cv = new ContentValues();
                    cv.put("DealerId", firstWarehouse.getDealerId() + "");
                    cv.put("CustomerId", firstWarehouse.getCustmerId() + "");
                    cv.put("CustomerName", firstWarehouse.getCustmerName() + "");
                    cv.put("OrderDate", firstWarehouse.getOrderDate() + "");
                    cv.put("EmployerId", firstWarehouse.getEmployerId() + "");
                    cv.put("EmployerName", firstWarehouse.getEmployerName() + "");
                    cv.put("OrderTotalPrice", firstWarehouse.getOrderTotalPrice() + "");
                    cv.put("PayType", firstWarehouse.getPayType() + "");
                    cv.put("DeliveryType", firstWarehouse.getDeliveryType() + "");
                    cv.put("OrderStatus", firstWarehouse.getOrderStatus() + "");
                    cv.put("DstAddr", firstWarehouse.getDstAddr() + "");
                    cv.put("Telephone", firstWarehouse.getTelephone() + "");
                    cv.put("CommunicatePeople", firstWarehouse.getCommunicatePeople() + "");
                    cv.put("OrderDate", firstWarehouse.getOrderDate() + "");
                    cv.put("OrderId", firstWarehouse.getOrderId() + "");
                    cv.put("HouseId", firstWarehouse.getHouseId() + "");
                    cv.put("HouseName", firstWarehouse.getHouseName() + "");
                    cv.put("DmsOrderId", firstWarehouse.getDmsOrderId() + "");
                    cv.put("OrderDetailList", firstWarehouse.getOrderDetailList() + "");
                    cv.put("modifyTime", firstWarehouse.getModifyTime() + "");
                    cv.put("Token", firstWarehouse.getToken() + "");
                    cv.put("comment", firstWarehouse.getComment() + "");
                    cv.put("storeHouseId", firstWarehouse.getStoreHouseId() + "");
                db.insertWithOnConflict("OrderList",null, cv, SQLiteDatabase.CONFLICT_REPLACE) ; //如果有记录，则更新，并返回1，否则返回0
              /*  if(hasOrder(firstWarehouse.getCustmerId() + "", firstWarehouse.getOrderDate() + "")){
                    Log.i(TAG, "replace:"+firstWarehouse.getOrderDate() + "");
                    // 生成的sql是 INSERT INTRO OR REPLACE INTO 这样的 (如果存在就替换存在的字段值. 存在的判断标准是主键冲突, 这里的主键是userId). 下面会介绍这个地方的方法
                    *//*db.update("OrderList",cv,"OrderTotalPrice=? and PayType=? and DeliveryType =? and OrderStatus =?" +
                            "DstAddr = ? and Telephone =? and CommunicatePeople = ? and OrderDate", new String[]{}) ; //如果有记录，则更新，并返回1，否则返回0*//*
                    db.replace("OrderList",null, cv) ; //如果有记录，则更新，并返回1，否则返回0
                } else{
                    Log.i(TAG, "insert:"+firstWarehouse.getOrderDate() + "");
                    db.insert("OrderList",null, cv) ; //如果有记录，则更新，并返回1，否则返回0
                }*/
            }
        }

        db.setTransactionSuccessful();
        db.endTransaction();
        Long b = System.currentTimeMillis();
        Log.i(TAG, String.valueOf(b - a));
        return 0;
    }

    public boolean hasData() {
        SQLiteDatabase db = DBHelper.open();
        Cursor cursor = db.rawQuery("select count(*)from OrderList", null);
        cursor.moveToFirst();
        Long count = cursor.getLong(0);
        if (count > 0) {
            cursor.close();
            Log.d(TAG, "hasOrder true");
            return true;
        } else {
            Log.d(TAG, "hasOrder false");
            cursor.close();
            return false;
        }
    }

    public long getMaxModifyTime() {
        long param = 0;
        SQLiteDatabase db = DBHelper.open();
        Cursor cursor = db.rawQuery("select max(modifyTime)from OrderList ", new String[]{});
        Log.d(TAG, "getMaxModifyTime:getCount" + cursor.getCount());
        if (cursor.moveToFirst()) {
            param = cursor.getLong(0);
        }
        cursor.close();
        Log.d(TAG, "getMaxModifyTime:param" + param);
        return param;
    }

    public void deleteAll() {
        SQLiteDatabase db = DBHelper.open();
        db.execSQL("DELETE FROM OrderList");
    }

    public List<FindOrderDetail> findAllPageOrder(int pageNow, int pageNum, int currentPage) {
        List<FindOrderDetail> list = new ArrayList<>();
        SQLiteDatabase db = DBHelper.open();
        String limit = String.valueOf((pageNow - 1) * pageNum) + "," + String.valueOf(pageNum);
        String selection = null;
        String[] selectionArgs = null;
        if (currentPage != 1) {
            selection = "OrderStatus=?";
            if (currentPage == 2) {
                selectionArgs = new String[]{String.valueOf("SUBM")};
            } else if (currentPage == 3) {
                selectionArgs = new String[]{String.valueOf("KEEP")};
            } else if (currentPage == 4) {
                selectionArgs = new String[]{String.valueOf("HANG")};
            }else if (currentPage == 5) {
                selectionArgs = new String[]{String.valueOf("CANC")};
            }else if (currentPage == 6) {
                selectionArgs = new String[]{String.valueOf("SNOE")};
            }
        }
        Cursor cursor = db.query("OrderList", null, selection, selectionArgs, null, null, "modifyTime desc", limit);//"5,9",第6行开始,返回9行数据
        if (pageNow > 1 && cursor.getCount() == 0) {
            ToastUtils.show("数据已加载完！");
        }
        Log.d(TAG, "cursor:" + cursor.getCount());
        for (int i = 0; i < cursor.getCount(); i++) {
            cursor.moveToNext();
            FindOrderDetail orderDetail = new FindOrderDetail();
            orderDetail.setDealerId(cursor.getString(1));
            orderDetail.setCustmerId(cursor.getString(2));
            orderDetail.setCustmerName(cursor.getString(3));
            orderDetail.setEmployerId(cursor.getString(4));
            orderDetail.setEmployerName(cursor.getString(5));
            orderDetail.setOrderTotalPrice(cursor.getString(6));
            orderDetail.setPayType(cursor.getString(7));
            orderDetail.setDeliveryType(cursor.getString(8));
            orderDetail.setOrderStatus(cursor.getString(9));
            orderDetail.setDstAddr(cursor.getString(10));
            orderDetail.setTelephone(cursor.getString(11));
            orderDetail.setCommunicatePeople(cursor.getString(12));
            orderDetail.setOrderDate(cursor.getString(13));
            orderDetail.setOrderId(cursor.getString(14));
            orderDetail.setHouseId(cursor.getString(15));
            orderDetail.setHouseName(cursor.getString(16));
            orderDetail.setDmsOrderId(cursor.getString(17));
            orderDetail.setOrderDetailList(cursor.getString(18));
            orderDetail.setModifyTime(cursor.getLong(19));
            orderDetail.setToken(cursor.getString(20));
            orderDetail.setComment(cursor.getString(21));
            orderDetail.setStoreHouseId(cursor.getString(22));
            //orderDetail.setId(cursor.getInt(0));
            list.add(orderDetail);
        }
        cursor.close();
        //db.close();
        Log.d(TAG, "findAllOrder:" + list.size());
        return list;
    }


    public List<FindOrderDetail> findAllDriverOrder(int pageNow, int pageNum, int currentPage) {
        List<FindOrderDetail> list = new ArrayList<>();
        SQLiteDatabase db = DBHelper.open();
        String limit = String.valueOf((pageNow - 1) * pageNum) + "," + String.valueOf(pageNum);
        String selection = null;
        String[] selectionArgs = null;
        if (currentPage != 1) {
            selection = "OrderStatus=?";
            if (currentPage == 2) {
                selectionArgs = new String[]{String.valueOf("SUBM")};
            } else if (currentPage == 3) {
                selectionArgs = new String[]{String.valueOf("KEEP")};
            } else if (currentPage == 4) {
                selectionArgs = new String[]{String.valueOf("0000")};
            }
        }
        Cursor cursor = db.query("OrderList", null, selection, selectionArgs, null, null, "modifyTime desc", limit);//"5,9",第6行开始,返回9行数据
        if (pageNow > 1 && cursor.getCount() == 0) {
            ToastUtils.show("数据已加载完！");
        }
        Log.d(TAG, "cursor:" + cursor.getCount());
        for (int i = 0; i < cursor.getCount(); i++) {
            cursor.moveToNext();
            FindOrderDetail orderDetail = new FindOrderDetail();
            orderDetail.setDealerId(cursor.getString(1));
            orderDetail.setCustmerId(cursor.getString(2));
            orderDetail.setCustmerName(cursor.getString(3));
            orderDetail.setEmployerId(cursor.getString(4));
            orderDetail.setEmployerName(cursor.getString(5));
            orderDetail.setOrderTotalPrice(cursor.getString(6));
            orderDetail.setPayType(cursor.getString(7));
            orderDetail.setDeliveryType(cursor.getString(8));
            orderDetail.setOrderStatus(cursor.getString(9));
            orderDetail.setDstAddr(cursor.getString(10));
            orderDetail.setTelephone(cursor.getString(11));
            orderDetail.setCommunicatePeople(cursor.getString(12));
            orderDetail.setOrderDate(cursor.getString(13));
            orderDetail.setOrderId(cursor.getString(14));
            orderDetail.setHouseId(cursor.getString(15));
            orderDetail.setHouseName(cursor.getString(16));
            orderDetail.setDmsOrderId(cursor.getString(17));
            orderDetail.setOrderDetailList(cursor.getString(18));
            orderDetail.setModifyTime(cursor.getLong(19));
            orderDetail.setToken(cursor.getString(20));
            orderDetail.setComment(cursor.getString(21));
            orderDetail.setStoreHouseId(cursor.getString(22));
            //orderDetail.setId(cursor.getInt(0));
            list.add(orderDetail);
        }
        cursor.close();
        //db.close();
        Log.d(TAG, "findAllOrder:" + list.size());
        return list;
    }

    public List<FindOrderDetail> findAllOrder() {
        List<FindOrderDetail> list = new ArrayList<>();
        SQLiteDatabase db = DBHelper.open();
        Cursor cursor = db.rawQuery("select * from OrderList", new String[]{});
        Log.d(TAG, "cursor:" + cursor.getCount());
        for (int i = 0; i < cursor.getCount(); i++) {
            cursor.moveToNext();
            FindOrderDetail orderDetail = new FindOrderDetail();
            orderDetail.setDealerId(cursor.getString(1));
            orderDetail.setCustmerId(cursor.getString(2));
            orderDetail.setCustmerName(cursor.getString(3));
            orderDetail.setEmployerId(cursor.getString(4));
            orderDetail.setEmployerName(cursor.getString(5));
            orderDetail.setOrderTotalPrice(cursor.getString(6));
            orderDetail.setPayType(cursor.getString(7));
            orderDetail.setDeliveryType(cursor.getString(8));
            orderDetail.setOrderStatus(cursor.getString(9));
            orderDetail.setDstAddr(cursor.getString(10));
            orderDetail.setTelephone(cursor.getString(11));
            orderDetail.setCommunicatePeople(cursor.getString(12));
            orderDetail.setOrderDate(cursor.getString(13));
            orderDetail.setOrderId(cursor.getString(14));
            orderDetail.setHouseId(cursor.getString(15));
            orderDetail.setHouseName(cursor.getString(16));
            orderDetail.setDmsOrderId(cursor.getString(17));
            orderDetail.setOrderDetailList(cursor.getString(18));
            orderDetail.setModifyTime(cursor.getLong(19));
            orderDetail.setToken(cursor.getString(20));
            orderDetail.setComment(cursor.getString(21));
            orderDetail.setStoreHouseId(cursor.getString(22));
            list.add(orderDetail);
        }
        cursor.close();
        Log.d(TAG, "findAllOrder:" + list.size());
        return list;
    }
}
